package com.jack.leetcode.每日一题;

import java.util.*;

/***
 * @author zhangjie
 * @date 2020/4/26 20:37
 */
public class 合并k个排序链表 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static ListNode mergeKLists(ListNode[] lists) {
        int n = lists.length;
        if (n <= 0) {
            return null;
        }
        ListNode tmp = new ListNode(0);
        ListNode result = tmp;
        Queue<ListNode> queue = new PriorityQueue<>(Comparator.comparing(l->l.val));
        for(ListNode list:lists){
            if(list!=null){
                queue.add(list);
            }
        }
        while(!queue.isEmpty()){
            tmp.next = queue.poll();
            tmp = tmp.next;
            if(tmp.next != null){
                queue.add(tmp.next);
            }
        }
        return result.next;
    }

    public static void main(String[] args) {
        ListNode[] tmp = new ListNode[3];
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(5);
        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
        ListNode l3 = new ListNode(2);
        l3.next = new ListNode(6);
        tmp[0] = l1;
        tmp[1] = l2;
        tmp[2] = l3;
        ListNode result = mergeKLists(tmp);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }
}
